package com.qd.panda.service.plate;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.panda.constant.PandaConstant;
import com.qd.common.panda.domain.entity.plate.PlateDTO;
import com.qd.common.panda.domain.entity.plate.UserPlateApprovalDTO;
import com.qd.common.panda.domain.enums.CarTypeEnum;
import com.qd.common.panda.util.PlateColorUtil;
import com.qd.hik.dto.HkBaseHttpResp;
import com.qd.hik.dto.driver.HkPlateReq;
import com.qd.hik.service.HkDriverService;
import com.qd.common.panda.domain.entity.hk.HkUserDTO;
import com.qd.panda.etc.dto.constant.VehicleColorConstant;
import com.qd.panda.mapper.plate.UserPlateApprovalMapper;
import com.qd.panda.model.HkUser;
import com.qd.panda.model.UserPlateApproval;
import com.qd.panda.model.UserPlateRelation;
import com.qd.panda.service.third.hk.HkUserService;
import com.qd.system.model.BaseUserInfo;
import com.qd.system.service.dict.MbUtil;
import com.qd.system.service.login.LoginUserService;
import com.qd.system.service.org.OrgService;
import com.qd.system.service.user.BaseUserInfoService;
import com.qd.system.util.FileConfirmUtil;
import com.qd.upload.constant.FileConfirmDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toSet;

/**
 * 车牌待审核
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class UserPlateApprovalService extends BaseService<UserPlateApprovalMapper, UserPlateApproval> {

    private static final String PREFIX_ID = "panda_user_plate_approval_approvalId_{0}";
    private static final String PREFIX_UNIQUE_PANDA_USER = "panda_user_plate_approval_plateNumber_{0}_userId_{1}";
    private final OrgService orgService;
    private final LoginUserService loginUserService;
    private final RedisTemplateUtil<UserPlateApproval> redisTemplateUtil;
    private final UserPlateRelationService userPlateRelationService;
    private final BaseUserInfoService baseUserInfoService;
    private final HkDriverService hkDriverService;
    private final HkUserService hkUserService;
    private final PlateService plateService;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserPlateApprovalDTO save(UserPlateApprovalDTO dto) {
        checkUnique(dto);
        final UserPlateApproval model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public UserPlateApprovalDTO update(UserPlateApprovalDTO dto) {
        checkUnique(dto);
        final UserPlateApproval historyModel = Optional.ofNullable(getById(dto.getApprovalId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final UserPlateApproval model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<UserPlateApproval> mList) {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<UserPlateApproval> mList) {
        final List<String> ids = mList.stream().map(UserPlateApproval::getApprovalId).collect(toList());
        final List<UserPlateApproval> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param approvalId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String approvalId) {
        final UserPlateApproval historyModel = Optional.ofNullable(getById(approvalId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(approvalId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(historyModel);
            historyModel.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        final List<UserPlateApproval> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(UserPlateApprovalDTO dto) {
        final QueryWrapper<UserPlateApproval> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param approvalId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String approvalId) {
        boolean exists = false;
        if (StringUtils.hasLength(approvalId)) {
            final UserPlateApproval model = getById(approvalId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param approvalId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserPlateApproval getById(String approvalId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, approvalId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(approvalId), UserPlateApproval.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param approvalId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserPlateApprovalDTO getByIdDto(String approvalId) {
        return Optional.ofNullable(getById(approvalId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public UserPlateApproval getOne(UserPlateApprovalDTO dto) {
        final QueryWrapper<UserPlateApproval> queryWrapper = createQueryWrapper(dto);
        UserPlateApproval model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public UserPlateApprovalDTO getOneDto(UserPlateApprovalDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<UserPlateApproval> getList(UserPlateApprovalDTO dto) {
        final QueryWrapper<UserPlateApproval> queryWrapper = createQueryWrapper(dto);
        final List<UserPlateApproval> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<UserPlateApprovalDTO> getListDto(UserPlateApprovalDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<UserPlateApprovalDTO> page(Page<UserPlateApproval> page, UserPlateApprovalDTO dto) {
        final QueryWrapper<UserPlateApproval> queryWrapper = createQueryWrapper(dto, "t1.");
        final IPage<UserPlateApprovalDTO> iPage = baseMapper.page(page, queryWrapper);
        Optional.ofNullable(iPage.getRecords()).ifPresent(l -> l.forEach(this::buildDisplay));
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 根据唯一性索引获得数据
     * param plateNumber
     * param userId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public UserPlateApproval getUniqueByPlateNumberAndUserId(String plateNumber, String userId) {
        final QueryWrapper<UserPlateApproval> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plate_number", plateNumber);
        queryWrapper.eq("user_id", userId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, plateNumber, userId);
        final UserPlateApproval model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), UserPlateApproval.class);
        queryWrapper.clear();
        return model;
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    @Transactional(readOnly = true)
    public void checkUnique(UserPlateApprovalDTO dto) {
        UserPlateApproval model = getUniqueByPlateNumberAndUserId(dto.getPlateNumber(), dto.getUserId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(UserPlateApprovalDTO dto, UserPlateApproval model) {
        if (!StringUtils.hasLength(dto.getApprovalId())) {
            throw new ApiException("数据已存在，请勿重复操作");
        }
        if (!dto.getApprovalId().equals(model.getApprovalId())) {
            throw new ApiException("数据已存在，请勿重复操作");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(UserPlateApproval model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getApprovalId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, model.getPlateNumber(), model.getUserId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<UserPlateApproval> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getApprovalId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        Set<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_PANDA_USER, model.getPlateNumber(), model.getUserId())).collect(toSet());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public UserPlateApprovalDTO modelToDto(UserPlateApproval model) {
        if (null == model) {
            return null;
        }
        final UserPlateApprovalDTO dto = new UserPlateApprovalDTO();
        dto.setApprovalId(model.getApprovalId());
        dto.setOriginalUserId(model.getOriginalUserId());
        dto.setOriginalMobile(model.getOriginalMobile());
        dto.setUserId(model.getUserId());
        dto.setUserMobile(model.getUserMobile());
        dto.setCarType(model.getCarType());
        dto.setVehicleColor(model.getVehicleColor());
        dto.setEtcCardId(model.getEtcCardId());
        dto.setAddTime(model.getAddTime());
        dto.setApprovalStatus(model.getApprovalStatus());
        dto.setApprovalTime(model.getApprovalTime());
        dto.setApprovalMsg(model.getApprovalMsg());
        dto.setVehicleLicensePositive(model.getVehicleLicensePositive());
        dto.setVehicleLicenseDeputy(model.getVehicleLicenseDeputy());
        dto.setAutoConfirmCharge(model.getAutoConfirmCharge());
        dto.setPlateNumber(model.getPlateNumber());
        dto.setApprovalUser(model.getApprovalUser());
        dto.setApprovalUnit(model.getApprovalUnit());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public UserPlateApproval dtoToModel(UserPlateApprovalDTO dto) {
        if (null == dto) {
            return null;
        }
        final UserPlateApproval model = new UserPlateApproval();
        model.setApprovalId(dto.getApprovalId());
        model.setOriginalUserId(dto.getOriginalUserId());
        model.setOriginalMobile(dto.getOriginalMobile());
        model.setUserId(dto.getUserId());
        model.setUserMobile(dto.getUserMobile());
        model.setCarType(dto.getCarType());
        model.setVehicleColor(dto.getVehicleColor());
        model.setEtcCardId(dto.getEtcCardId());
        model.setAddTime(dto.getAddTime());
        model.setApprovalStatus(dto.getApprovalStatus());
        model.setApprovalTime(dto.getApprovalTime());
        model.setApprovalMsg(dto.getApprovalMsg());
        model.setVehicleLicensePositive(dto.getVehicleLicensePositive());
        model.setVehicleLicenseDeputy(dto.getVehicleLicenseDeputy());
        model.setAutoConfirmCharge(dto.getAutoConfirmCharge());
        model.setPlateNumber(dto.getPlateNumber());
        model.setApprovalUser(dto.getApprovalUser());
        model.setApprovalUnit(dto.getApprovalUnit());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(UserPlateApprovalDTO dto) {
        if (StringUtils.hasLength(dto.getApprovalUser())) {
            dto.setApprovalUserDisplay(loginUserService.idToDisplay(dto.getApprovalUser()));
        }
        if (StringUtils.hasLength(dto.getApprovalUnit())) {
            dto.setApprovalUnitDisplay(orgService.idToDisplay(dto.getApprovalUnit()));
        }
        if (null != dto.getApprovalStatus()) {
            switch (dto.getApprovalStatus()) {
                case 0:
                    dto.setApprovalStatusDisplay("待审批");
                    break;
                case 1:
                    dto.setApprovalStatusDisplay("审批通过");
                    break;
                case 2:
                    dto.setApprovalUserDisplay("审批未通过");
                    break;
                default:
                    dto.setApprovalStatusDisplay("未知");
                    break;
            }
        }
        if (StringUtils.hasLength(dto.getAutoConfirmCharge())) {
            dto.setAutoConfirmChargeDisplay(MbUtil.idToDisplay(dto.getAutoConfirmCharge()));
        }
        if (null != dto.getCarType()) {
            dto.setCarTypeDisplay(CarTypeEnum.idToDisplay(dto.getCarType()));
        }
        if (StringUtils.hasLength(dto.getEtcPay())) {
            dto.setEtcPayDisplay(MbUtil.idToDisplay(dto.getEtcPay()));
        }
        if (null != dto.getVehicleColor()) {
            dto.setVehicleColorDisplay(VehicleColorConstant.idToDisplay(dto.getVehicleColor()));
        }
        if (StringUtils.hasLength(dto.getVehicleLicensePositive())) {
            dto.setVehicleLicensePositiveDisplay(FileConfirmUtil.getImageFile(dto.getVehicleLicensePositive()));
        }
        if (StringUtils.hasLength(dto.getVehicleLicenseDeputy())) {
            dto.setVehicleLicenseDeputyDisplay(FileConfirmUtil.getImageFile(dto.getVehicleLicenseDeputy()));
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<UserPlateApprovalDTO> modelToDtoList(List<UserPlateApproval> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<UserPlateApproval> dtoToModelList(List<UserPlateApprovalDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<UserPlateApproval> createQueryWrapper(UserPlateApprovalDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<UserPlateApproval> createQueryWrapper(UserPlateApprovalDTO dto, String tableAlias) {
        final QueryWrapper<UserPlateApproval> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getOriginalMobile())) {
                queryWrapper.eq(tableAlias + "original_mobile", dto.getOriginalMobile());
            }
            if (StringUtils.hasLength(dto.getUserMobile())) {
                queryWrapper.eq(tableAlias + "user_mobile", dto.getUserMobile());
            }
            if (StringUtils.hasLength(dto.getUserId())) {
                queryWrapper.eq(tableAlias + "user_id", dto.getUserId());
            }
            if (StringUtils.hasLength(dto.getPlateNumber())) {
                queryWrapper.eq(tableAlias + "plate_number", dto.getPlateNumber());
            }
            if (StringUtils.hasLength(dto.getApprovalUser())) {
                queryWrapper.eq(tableAlias + "approval_user", dto.getApprovalUser());
            }
            if (StringUtils.hasLength(dto.getApprovalUnit())) {
                queryWrapper.eq(tableAlias + "approval_unit", dto.getApprovalUnit());
            }
            if (null != dto.getApprovalStatus()) {
                queryWrapper.eq(tableAlias + "approval_status", dto.getApprovalStatus());
            }
            if (StringUtils.hasLength(dto.getApprovalStatusList())) {
                Object[] approvalStatusList = dto.getApprovalStatusList().split(",");
                queryWrapper.in("approval_status", approvalStatusList);
            }
        }
        queryWrapper.orderByDesc(tableAlias + "approval_time");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<UserPlateApproval> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<UserPlateApproval> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(UserPlateApproval::getApprovalId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void plateApproval(UserPlateApprovalDTO dto) {
        UserPlateRelation userPlateRelation = userPlateRelationService.getUniqueByPlateNumber(dto.getPlateNumber());
        if (null == userPlateRelation) {
            throw new ApiException("当前车牌号还未添加,请直接添加");
        }
        String userId = userPlateRelation.getUserId();
        userPlateRelation.freeData();

        UserPlateApproval userPlateApproval = getUniqueByPlateNumberAndUserId(dto.getPlateNumber(), dto.getUserId());
        if (null != userPlateApproval) {
            if (userPlateApproval.getApprovalStatus().equals(PandaConstant.APPROVAL_STATUS_0)) {
                throw new ApiException("正在审核中，请勿重复提交");
            }
            if (userPlateApproval.getApprovalStatus().equals(PandaConstant.APPROVAL_STATUS_1)) {
                throw new ApiException("审核已通过");
            }
            if (userPlateApproval.getApprovalStatus().equals(PandaConstant.APPROVAL_STATUS_2)) {
                throw new ApiException("审核未通过");
            }
        }
        dto.setOriginalUserId(userId);
        BaseUserInfo baseUserInfo = Optional.ofNullable(baseUserInfoService.getById(userId)).orElseThrow(() -> new ApiException("用户信息异常"));
        dto.setOriginalMobile(baseUserInfo.getMobile());
        FileConfirmDTO fileConfirmDto = FileConfirmUtil.singleFileConfirm(dto.getVehicleLicensePositive(), ConstantDto.ATTACHMENTTYPE_2);
        if (null == fileConfirmDto) {
            throw new ApiException("文件ID不存在[" + dto.getVehicleLicensePositive() + "]");
        }
        dto.setVehicleLicensePositive(fileConfirmDto.getOfficialFile());
        fileConfirmDto = FileConfirmUtil.singleFileConfirm(dto.getVehicleLicenseDeputy(), ConstantDto.ATTACHMENTTYPE_2);
        if (null == fileConfirmDto) {
            throw new ApiException("文件ID不存在[" + dto.getVehicleLicenseDeputy() + "]");
        }
        dto.setVehicleLicenseDeputy(fileConfirmDto.getOfficialFile());
        save(dto);
    }

    @Transactional(rollbackFor = Exception.class)
    public void approval(UserPlateApprovalDTO dto) {
        UserPlateApprovalDTO userPlateApprovalDTO = Optional.ofNullable(getByIdDto(dto.getApprovalId())).orElseThrow(() -> new ApiException("待审核ID值错误"));
        if (!Objects.equals(userPlateApprovalDTO.getApprovalStatus(), PandaConstant.APPROVAL_STATUS_0)) {
            throw new ApiException("请勿重复审核");
        }
        userPlateApprovalDTO.setApprovalStatus(dto.getApprovalStatus());
        userPlateApprovalDTO.setApprovalUser(dto.getApprovalUser());
        userPlateApprovalDTO.setApprovalUnit(dto.getApprovalUnit());
        userPlateApprovalDTO.setApprovalMsg(Optional.ofNullable(dto.getApprovalMsg()).orElse("审批通过"));
        userPlateApprovalDTO.setApprovalTime(LocalDateTime.now());
        update(userPlateApprovalDTO);

        if (dto.getApprovalStatus().equals(PandaConstant.APPROVAL_STATUS_1)) {
            updateUserPlateRelation(userPlateApprovalDTO);
            updateVehicleColor(dto, userPlateApprovalDTO);
            buildHkPlateNumber(userPlateApprovalDTO);
        }
        userPlateApprovalDTO.freeData();
    }

    private void updateUserPlateRelation(UserPlateApprovalDTO userPlateApprovalDTO) {
        UserPlateRelation userPlateRelation = Optional.ofNullable(userPlateRelationService.getUniqueByPlateNumber(userPlateApprovalDTO.getPlateNumber())).orElseThrow(() -> new ApiException("数据异常"));
        userPlateRelation.setUserId(userPlateApprovalDTO.getUserId());
        userPlateRelation.setAddTime(LocalDateTime.now());
        userPlateRelationService.update(userPlateRelationService.modelToDto(userPlateRelation));
        userPlateRelation.freeData();
    }

    private void updateVehicleColor(UserPlateApprovalDTO dto, UserPlateApprovalDTO userPlateApprovalDTO) {
        if (null != dto.getVehicleColor()) {
            PlateDTO plateDTO = Optional.ofNullable(plateService.getByIdDto(userPlateApprovalDTO.getPlateNumber())).orElseThrow(() -> new ApiException("车牌号值错误"));
            boolean isUpdate = false;
            if (null == plateDTO.getVehicleColor()) {
                plateDTO.setVehicleColor(dto.getVehicleColor());
                isUpdate = true;
            } else if (!plateDTO.getVehicleColor().equals(dto.getVehicleColor())) {
                plateDTO.setVehicleColor(dto.getVehicleColor());
                isUpdate = true;
            }
            if (isUpdate) {
                plateService.update(plateDTO);
            }
            plateDTO.freeData();
        }
    }

    private void buildHkPlateNumber(UserPlateApprovalDTO userPlateApprovalDTO) {
        HkUser oldHkUser = hkUserService.getById(userPlateApprovalDTO.getOriginalUserId());
        if (null == oldHkUser) {
            HkUserDTO hkUserDTO = hkUserService.createHkUser(userPlateApprovalDTO.getOriginalUserId(), userPlateApprovalDTO.getOriginalMobile());
            oldHkUser = hkUserService.dtoToModel(hkUserDTO);
        }

        HkPlateReq req = new HkPlateReq();
        req.setDriverId(oldHkUser.getDriverId());
        req.setPlateNo(userPlateApprovalDTO.getPlateNumber());
        req.setPlateColor(PlateColorUtil.pandaToHk(userPlateApprovalDTO.getVehicleColor()));
        HkBaseHttpResp<?> resp = hkDriverService.delPlate(req);
        req.freeData();
        //这你如果没有可能出现删除失败的情况
        log.info("删除用户车牌失败,状态: {}", resp.isSuccess());

        HkUser hkUser = hkUserService.getById(userPlateApprovalDTO.getUserId());
        if (null == hkUser) {
            HkUserDTO hkUserDTO = hkUserService.createHkUser(userPlateApprovalDTO.getUserId(), userPlateApprovalDTO.getUserMobile());
            hkUser = hkUserService.dtoToModel(hkUserDTO);
        }
        req = new HkPlateReq();
        req.setDriverId(hkUser.getDriverId());
        req.setPlateNo(userPlateApprovalDTO.getPlateNumber());
        req.setPlateColor(PlateColorUtil.pandaToHk(userPlateApprovalDTO.getVehicleColor()));
        resp = hkDriverService.addPlate(req);
        req.freeData();
        if (!resp.isSuccess()) {
            throw new ApiException("添加用户车牌失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void deletePlateApproval(List<String> ids) {
        for (String id : ids) {
            UserPlateApproval userPlateApproval = getById(id);
            if (userPlateApproval.getApprovalStatus().equals(PandaConstant.APPROVAL_STATUS_1)) {
                throw new ApiException("车牌号[" + userPlateApproval.getPlateNumber() + "]已通过审核,不能删除");
            }
            removeById(id);
        }
    }
}